import req from '../utils/request'
import {useStore} from "@/stores";
import {
    authPlatformTokenUrl,
    authUserAssetLoadUrl,
    getUserSessionByIdUrl,
    authUserAuthorizeUrl,
    getAuthUserInfoUrl,
    authUserAutoAuthorizeUrl,
    getCaptchaCodeUrl,
    authUserLoginUrl,
    authUserLogoutUrl,
    authUserTokenUrl,
    deleteAssetUrl,
    loadAssetLevelPageUrl,
    loadAssetLevelUrl,
    loadAssetOfHolderPageUrl,
    loadAssetPageUrl,
    loadAttributeOfAssetUrl,
    loadHolderForAssetPageUrl,
    loadMoveAssetPageUrl,
    moveAssetUrl,
    platformUpdateCacheUrl,
    platformAddUrl,
    platformApplicationPageUrl,
    platformLoadUserPageUrl,
    platformLookupUrl,
    grantPlatformUrl,
    platformQueryPageUrl,
    authPlatformQueryPageUrl,
    platformTenantPageUrl,
    platformTerminalPageUrl,
    platformUpdateUrl,
    realmAddUserGroupToUserUrl,
    realmAddUserToUserGroupUrl,
    realmSaveGroupsOfPlatformUrl,
    realmAssignGroupsToPlatformUrl,
    realmAssignPlatsToGroupUrl,
    realmLoadUserPageUrl,
    realmLookupUrl,
    realmQueryPageUrl,
    realmRemoveUserFromUserGroupUrl,
    realmRemoveUserGroupFromPlatformUrl,
    realmSaveUrl,
    realmUserGroupLevelPageUrl,
    realmUserGroupOfRealmListUrl,
    realmUserGroupOfPlatformListUrl,
    realmUserLookupUrl,
    realmUserSaveUrl,
    updateUserCacheUrl,
    resetUserPasswordUrl,
    saveRealmUserAccountUrl,
    lookupRealmUserAccountUrl,
    realQueryCanAssignPlatformsUrl,
    realQueryPlatformsInGroupUrl,
    realRemoveUserGroupFromUserUrl,
    removeAssetOfHolderUrl,
    removeAttributeOfAssetUrl,
    saveAssetOfHolderUrl,
    saveAssetUrl,
    saveAttributeOfAssetUrl,
    saveHolderForAssetUrl,
} from "@/apis/url";

export const request = async (params: any, clientId: string | undefined = undefined,
                              clientSecret: string | undefined = undefined,
                              platform: string | undefined = undefined) => {
    let result: any;
    try {
        const store = useStore();
        const cred = store.getCredential();

        if (!params.headers) {
            params.headers = {};
        }

        if (cred && cred.accessToken) {
            params.headers['access_token'] = cred.accessToken;
        }

        params.headers['client_id'] = clientId || import.meta.env.VITE_APP_CLIENT_ID;
        params.headers['client_secret'] = clientSecret || import.meta.env.VITE_APP_CLIENT_SECRET;
        params.headers['terminal_id'] = 'WEB';
        params.headers['platform'] = platform || import.meta.env.VITE_APP_PLATFORM;

        console.log('--- request, 开始调用接口', params);
        result = await req(params);
        console.log('--- request, 调用接口返回', result);
        result = result.data;
        if (101000 == result.code) {
            localStorage.removeItem("user-token")
            window.location.href = window.location.origin;
        }
    } catch (e) {
        console.log('--- response, 调用接口异常', e);
        result = {
            code: 502,
            message: '网络异常,请稍后再试!',
        }
    }
    return result;
}

export const requestRealm = async (params: any) => {
    const store = useStore();
    const currentRealm: any = store.getCurrentRealms();
    params.data['realmId'] = params.realmId || currentRealm?.id;
    return await request(params);
}

export const requestPlatform = async (params: any) => {
    const store = useStore();
    const currentRealm: any = store.getCurrentRealms();
    const currentPl: any = store.getCurrentPlatform();
    params.data['platformId'] = currentPl?.id;
    params.data['realmId'] = currentRealm?.id;
    return await request(params);
}

export const getCaptchaCode = async () => request(
    {url: getCaptchaCodeUrl(''), method: 'post'});

export const userLogin = async (params: any) => request(
    {url: authUserLoginUrl(''), method: 'post', data: params});

/**
 * 下面是单点登录接口
 * @param params
 * @param ctx
 * @param codeInfo
 */
export const userAuthorize = async (params: any, ctx: any, codeInfo: any) => request({
    url: authUserAuthorizeUrl(''),
    method: 'post',
    data: params,
    headers: {
        captcha_key: codeInfo.key,
        captcha_code: codeInfo.code,
    }
}, ctx.clientId, ctx.clientSecret, ctx.platform);

export const getAuthUserInfo = async (accessToken: string) => request({
    url: getAuthUserInfoUrl(''),
    method: 'post',
    headers: {
        access_token: accessToken,
    },
    data: {}
});

export const userAutoAuthorize = async (clientId: string,
                                        clientSecret: string,
                                        platform: string) => request({
    url: authUserAutoAuthorizeUrl(''),
    method: 'post',
    data: {}
}, clientId, clientSecret, platform);

export const userToken = async (code: any) => request(
    {url: authUserTokenUrl('') + `?code=${code}`, method: 'post', data: {}});

export const userLogout = async () => request(
    {url: authUserLogoutUrl(''), method: 'post', data: {}});

export const platformToken = async (id: any) => request(
    {url: authPlatformTokenUrl('', id), method: 'post', data: {}});

/**
 * 动态路由接口
 */
export const loadAuthUserAsset = async () => request(
    {url: authUserAssetLoadUrl(''), method: 'post'})

export const getUserSessionById = async (params: any) => request(
    {url: getUserSessionByIdUrl(''), method: 'post', data: params})

// --------------------- 下面是资源操作接口
/**
 * 保存资源持有信息
 * @param params {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * holdId: '',
 * holdType: '',
 * assets: [{
 *  assetId: '',
 *  assetType: '',
 * }
 * ]
 * }
 * @returns
 */
export const saveAssetOfHolder = async (params: any) => request(
    {url: saveAssetOfHolderUrl(''), method: 'post', data: params});

/**
 * 保存资源持有信息
 * @param params {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * assetId: '',
 * assetType: '',
 * holders: [{
 *  holdId: '',
 *  holdType: '',
 * }
 * ]
 * }
 * @returns
 */
export const saveHolderForAsset = async (params: any) => request(
    {url: saveHolderForAssetUrl(''), method: 'post', data: params});

/**
 * 查询指定资源的信息（比如属性）
 * @param params {
 * realmId: '',
 * platformId: '',
 * tenantId: '',
 * assetId: '1',
 * assetType: 'PERMIT',
 * }
 * @returns {
 * code: 0,
 * message: '',
 * data: {
 * id: '',
 * code: '',
 * name: '',
 * subType: '',
 * parentId: '',
 * props: {} // 资源属性
 * }
 * }
 */
export const lookupAsset = async (params: any) => requestPlatform(
    {url: '/api/asset/lookup', method: 'post', data: params});

/**
 * 查找指定资源信息，包括其完整的分层信息（包含子节点）
 * @param params {
 * realmId: '',
 * platformId: '',
 * tenantId: '',
 * assetId: '1',
 * assetType: 'PERMIT',
 * }
 * @returns  {
 * code: 0,
 * message: '',
 * data: {
 * id: '',
 * code: '',
 * name: '',
 * subType: '',
 * parentId: '',
 * props: {} // 资源属性
 * children: [] // 子资源
 * }
 * }
 */
export const lookupAssetLevel = async (params: any) => requestPlatform(
    {url: '/api/asset/Level/lookup', method: 'post', data: params});

/**
 * 分页查询指定资源，此方法不会对资源分层，只查询满足条件的所有资源
 * @param params {
 * server: '',
 * targetId: '',
 * tenantId: '',
 * assetId: '1',
 * assetType: 'PERMIT',
 * parentId: '',
 * name: '',
 * code: '',
 * state: 0,
 * }
 * @returns {
 * code: 0,
 * message: '',
 * data: [{
 * id: '',
 * code: '',
 * name: '',
 * subType: '',
 * parentId: '',
 * }]
 * }
 */
export const loadAssetPage = async (params: any) => request(
    {url: loadAssetPageUrl(''), method: 'post', data: params});

/**
 * 按层级分页查询资源信息，必须传入父资源ID，如果父资源ID为空，则查询顶层所有资源
 * @param params {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * assetId: '1',
 * assetType: 'PERMIT',
 * parentId: '',
 * name: '',
 * code: '',
 * state: 0,
 * filter: {
 *     holds: [
 *         {
 *             id: '',
 *             type: '',
 *         }
 *     ],
 *     targets: [
 *         {
 *             id: '',
 *             type: '',
 *         }
 *     ],
 * }
 * }
 * @returns {
 * code: 0,
 * message: '',
 * data: [{
 * id: '',
 * code: '',
 * name: '',
 * subType: '',
 * parentId: '',
 * }]
 * }
 */
export const loadAssetLevelPage = async (params: any) => request(
    {url: loadAssetLevelPageUrl(''), method: 'post', data: params});

/**
 * 获取指定资源所有信息，包括其层次结构信息
 * @param params  {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * assetId: '1',
 * assetType: 'PERMIT',
 * name: '',
 * }
 */
export const loadAssetLevel = async (params: any) => request(
    {url: loadAssetLevelUrl(''), method: 'post', data: params});

export const loadMoveAssetPage = async (params: any) => request(
    {url: loadMoveAssetPageUrl(''), method: 'post', data: params});

export const moveAsset = async (asset: any) => request(
    {url: moveAssetUrl(''), method: 'post', data: asset});

/**
 * 保存资源信息
 * @param asset 资源信息 {
 *     server: '',
 *     targetId: '',
 *     asset: {}
 * }
 */
export const saveAsset = async (asset: any) => request(
    {url: saveAssetUrl(''), method: 'post', data: asset});

/**
 * 删除资源
 * @param asset {
 *     server: '',
 *     targetId: '',
 *     asset: {
 *         id: '',
 *         type: '',
 *     }
 * }
 */
export const deleteAsset = async (asset: any) => requestPlatform(
    {url: deleteAssetUrl(''), method: 'post', data: asset});

/**
 * 分页查询指定资源拥有的所有资源信息，比如查询指定分组下所有的权限信息
 * @param params {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * current: 1,
 * pageSize: 10,
 * holdId: '1',
 * holdType: 'GROUP',
 * assetType: 'PERMIT'
 * }
 * @returns
 */
export const loadAssetsForHolderByPage = async (params: any) => request(
    {url: loadAssetOfHolderPageUrl(''), method: 'post', data: params});

/**
 * 分页查询拥有指定资源的所有资源信息，比如查询拥有指定权限的所有分组信息
 * @param params {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * current: 1,
 * pageSize: 10,
 * assetId: '1',
 * assetType: 'PERMIT',
 * holdType: 'GROUP'
 * }
 * @returns
 */
export const loadHolderForAssetPage = async (params: any) => request(
    {url: loadHolderForAssetPageUrl(''), method: 'post', data: params});

/**
 * 移除持有的资源
 * @param params {
 * server: '',   // targetId所属服务类型
 * targetId: '', // 资源所在目标ID
 * tenantId: '',
 * holeId: '',
 * holdType: '',
 * assets: [{
 *  assetId: '',
 *  assetType: '',
 * }
 * ]
 * }
 * @returns
 */
export const removeAssetOfHolder = async (params: any) => request(
    {url: removeAssetOfHolderUrl(''), method: 'post', data: params});

/**
 * 读取资源属性
 * @param params {
 *     server: '',   // targetId所属服务类型
 *     targetId: '', // 资源所在目标ID
 *     assetId: '',
 *     assetType: '',
 * }
 * @return {
 *     assetId: '',
 *     assetType: '',
 *     props: {}
 * }
 */
export const loadAttributeOfAsset = async (params: any) => request(
    {url: loadAttributeOfAssetUrl(''), method: 'post', data: params});

/**
 * 保存资源属性
 * @param params {
 *     server: '',   // targetId所属服务类型
 *     targetId: '', // 资源所在目标ID
 *     assetId: '',
 *     assetType: '',
 *     props: {
 *         name: value
 *     }
 * }
 */
export const saveAttributeOfAsset = async (params: any) => request(
    {url: saveAttributeOfAssetUrl(''), method: 'post', data: params});

/**
 * 删除资源属性
 * @param params {
 *     server: '',   // targetId所属服务类型
 *     targetId: '', // 资源所在目标ID
 *     assetId: '',
 *     assetType: '',
 *     props: [
 *         '11','22'
 *     ]
 * }
 */
export const removeAttributeOfAsset = async (params: any) => request(
    {url: removeAttributeOfAssetUrl(''), method: 'post', data: params});

// --------------------- 下面领域和领域用户相关操作接口

export const lookupRealm = async (pl: any) => request(
    {url: realmLookupUrl(''), method: 'post', data: pl});
export const lookupRealmUser = async (pl: any) => requestRealm(
    {url: realmUserLookupUrl(''), method: 'post', data: pl});

/**
 * 分页查询领域信息
 * @param params {
 *  name: ''
 * }
 * @returns
 */
export const loadRealmByPage = async (params: any) => request(
    {url: realmQueryPageUrl(''), method: 'post', data: params})

export const saveRealmUser = async (user: any) => requestRealm(
    {url: realmUserSaveUrl(''), method: 'post', data: user})

export const updateUserCache = async (user: any) => requestRealm(
    {url: updateUserCacheUrl(''), method: 'post', data: user})
export const resetUserPassword = async (user: any) => requestRealm(
    {url: resetUserPasswordUrl(''), method: 'post', data: user})

export const saveRealmUserAccount = async (user: any) => requestRealm(
    {url: saveRealmUserAccountUrl(''), method: 'post', data: user})
export const lookupRealmUserAccount = async (user: any) => requestRealm(
    {url: lookupRealmUserAccountUrl(''), method: 'post', data: user})

export const saveRealm = async (realm: any) => request(
    {url: realmSaveUrl(''), method: 'post', data: realm});

/**
 * 把领域用户分组分配给平台
 * @param data {
 * realmId: '',
 * tenantId: '',
 * platformId: '',
 * items: []
 * }
 */
export const assignRealmUserGroupsToPlatform = async (data: any) => requestRealm(
    {url: realmAssignGroupsToPlatformUrl(''), method: 'post', data: data});
export const realmSaveGroupsOfPlatform = async (data: any) => request(
    {url: realmSaveGroupsOfPlatformUrl(''), method: 'post', data: data});
export const assignPlatformsToRealmUserGroup = async (data: any) => requestRealm(
    {url: realmAssignPlatsToGroupUrl(''), method: 'post', data: data});
export const realQueryCanAssignPlatformsPage = async (data: any) => requestRealm(
    {url: realQueryCanAssignPlatformsUrl(''), method: 'post', data: data});
export const realQueryPlatformsInGroupPage = async (data: any) => requestRealm(
    {url: realQueryPlatformsInGroupUrl(''), method: 'post', data: data});

/**
 * 异常分配给平台的领域用户分组
 * @param data {
 *     realmId: '',
 *     platformId: '',
 *     groups: [],
 * }
 */
export const removeRealmUserGroupFromPlatform = async (data: any) => requestRealm(
    {url: realmRemoveUserGroupFromPlatformUrl(''), method: 'post', data: data});

/**
 * 读取领域用户分组列表
 * @param params {
 * realmId: '',
 * tenantId: '',
 * platformId: '',
 * name: '',
 * }
 */
export const loadRealmUserGroupOfRealmList = async (params: any) => request(
    {url: realmUserGroupOfRealmListUrl(''), method: 'post', data: params});

/**
 * 读取已经分配给平台的领域用户分组
 * @param params {
 * realmId: '',
 * tenantId: '',
 * platformId: '',
 * name: '',
 * }
 */
export const loadRealmUserGroupOfPlatformList = async (params: any) => request(
    {url: realmUserGroupOfPlatformListUrl(''), method: 'post', data: params});

/**
 * 分页查询领域用户信息
 *
 * @param params {
 * current: 1,
 * pageSize: 10,
 * realmId: '',
 * tenantId: '',
 * platformId: '',
 * name: '',
 * state: 0,
 * groups: []  // 用户分组信息
 * filter: {
 *     groups: []
 * }
 * }
 * @returns
 */
export const loadRealmUserPage = async (params: any) => request(
    {url: realmLoadUserPageUrl(''), method: 'post', data: params});

export const platformLoadUserPage = async (params: any) => request(
    {url: platformLoadUserPageUrl(''), method: 'post', data: params});

/**
 * 按层次分页读取领域用户的分组，根据传入的平台ID过滤掉已经加入平台的分组
 * 此方法会根据parentId查询其子分组信息
 *
 * @param params {
 *     realmId: '',
 *     parentId: '',
 *     current: 1,
 *     pageSize: 10,
 *     name: ''
 *     filter: {
 *         platformId: '',
 *         groupId: '',
 *     }
 * }
 */
export const loadRealmUserGroupLevelPage = async (params: any) => request(
    {url: realmUserGroupLevelPageUrl(''), method: 'post', data: params});

/**
 * 把领域用户分组分配给用户
 * @param params {
 *     realmId: '',
 *     userId: '',
 *     groups: [],
 * }
 */
export const addRealUserGroupToUser = async (params: any) => request(
    {url: realmAddUserGroupToUserUrl(''), method: 'post', data: params});

/**
 * 把分组列表从指定用户中移除
 * @param params {
 *     realmId: '',
 *     userId: '',
 *     groups: [],
 * }
 */
export const realmRemoveUserGroupFromUser = async (params: any) => request(
    {url: realRemoveUserGroupFromUserUrl(''), method: 'post', data: params});
/**
 * 把用户从指定分组中移除
 * @param params {
 *     realmId: '',
 *     groupId: '',
 *     users: [],
 * }
 */
export const realmRemoveUserFromUserGroup = async (params: any) => request(
    {url: realmRemoveUserFromUserGroupUrl(''), method: 'post', data: params});

/**
 * 把用户加入指定用户分组
 * @param params {
 *     realmId: '',
 *     groupId: '',
 *     users: []
 * }
 */
export const addUserToRealUserGroup = async (params: any) => request(
    {url: realmAddUserToUserGroupUrl(''), method: 'post', data: params});

export const loadRealmSetting = async (params: any) => request(
    {url: '/api/realm/setting/load', method: 'post', data: params});

export const saveRealmSetting = async (setting: any) => request(
    {url: '/api/realm/setting/save', method: 'post', data: setting});

export const deleteRealmSetting = async (grp: any) => request(
    {url: '/api/realm/setting/delete', method: 'post', data: grp});

// --------------------- 下面是平台相关操作接口
/**
 * 分页查询平台信息
 * @param params {
 * realmId: '',
 * tenantId: '',
 * name: '',
 * state: 0,
 * }
 * @returns
 */
export const loadPlatformPage = async (params: any) => request(
    {url: platformQueryPageUrl(''), method: 'post', data: params});
export const authPlatformQueryPage = async (params: any) => request(
    {url: authPlatformQueryPageUrl(''), method: 'post', data: params});
export const grantPlatform = async (params: any) => request(
    {url: grantPlatformUrl(''), method: 'post', data: params});
export const loadPlatformTenantPage = async (params: any) => request(
    {url: platformTenantPageUrl(''), method: 'post', data: params})
export const loadPlatformApplicationPage = async (params: any) => request(
    {url: platformApplicationPageUrl(''), method: 'post', data: params})
export const loadPlatformTerminalPage = async (params: any) => request(
    {url: platformTerminalPageUrl(''), method: 'post', data: params})
export const lookupPlatform = async (pl: any) => request(
    {url: platformLookupUrl(''), method: 'post', data: pl})

export const platformUpdateCache = async (pl: any) => request(
    {url: platformUpdateCacheUrl(''), method: 'post', data: pl})
export const addPlatform = async (pl: any) => request(
    {url: platformAddUrl(''), method: 'post', data: pl})
export const updatePlatform = async (pl: any) => request(
    {url: platformUpdateUrl(''), method: 'post', data: pl})

export const loadCallLogPage = async (params: any) => requestPlatform(
    {url: '/uni-auth/v1/token/log/query/call/page', method: 'post', data: params})
export const loadLoginLogPage = async (params: any) => requestPlatform(
    {url: '/uni-auth/v1/token/log/query/login/page', method: 'post', data: params})
export const loadAuditLogPage = async (params: any) => requestPlatform(
    {url: '/uni-center/v1/log/query/audit/page', method: 'post', data: params})
export const loadSystemLogPage = async (params: any) => request(
    {url: '/uni-center/v1/log/query/system/page', method: 'post', data: params})
